
package slevnik;

import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * Comparator used to order items by distance to given city.
 *
 * @author Martin Penak
 */
public class CityDistancesComparator implements Comparator {

    private String city = null;

    private List<String> cities;

    private Map<String, Integer> distances;

    /**
     * Constructor for CityDistanceComparator
     * Constructor uses DistanceParser to calculate distances from cities to given city
     * @param city city used to calculate distances
     * @param cities list of cities used to calculate distances
     */
    public CityDistancesComparator(String city, List<String> cities) {
        this.city = city;
        this.cities = cities;
        distances = DistanceParser.getDistances(city, cities);
    } 

    @Override
    public int compare(Object o1, Object o2) {

        if (!(o1 instanceof Item)) {
             return 0;
        }

        if (!(o2 instanceof Item)) {
            return 0;
        }
        
        Item item1 = (Item) o1;
        Item item2 = (Item) o2;             
                
        int distance1 = distances.get(item1.getCity().toLowerCase());
        int distance2 = distances.get(item2.getCity().toLowerCase());

        if (distance1 == distance2) {
            return item1.getId() - item2.getId();
        } else {
            return distance1 - distance2;
        }
    }

}
